import { ref, computed } from 'vue';
import type { User, LoginRequest, RegisterRequest } from '@vue-turbo-stack/shared';
import { trpc } from '@/utils/trpc';
import { AuthUtils } from '@/utils/auth';

// 认证状态管理
const user = ref<User | null>(AuthUtils.getUser());
const isLoading = ref(false);
const error = ref<string | null>(null);

// 计算属性
const isAuthenticated = computed(() => !!user.value);

// 登录
async function login(credentials: LoginRequest) {
  isLoading.value = true;
  error.value = null;
  
  try {
    const result = await trpc.login(credentials);
    
    // 保存认证信息
    AuthUtils.saveAuth(result.token, result.user);
    user.value = result.user;
    
    return result;
  } catch (err: any) {
    error.value = err.message || 'Login failed';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

// 注册
async function register(userData: RegisterRequest) {
  isLoading.value = true;
  error.value = null;
  
  try {
    const result = await trpc.register(userData);
    
    // 保存认证信息
    AuthUtils.saveAuth(result.token, result.user);
    user.value = result.user;
    
    return result;
  } catch (err: any) {
    error.value = err.message || 'Registration failed';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

// 登出
function logout() {
  AuthUtils.clearAuth();
  user.value = null;
  error.value = null;
}

// 获取用户资料
async function fetchProfile() {
  if (!AuthUtils.isAuthenticated()) {
    return;
  }
  
  isLoading.value = true;
  error.value = null;
  
  try {
    const token = AuthUtils.getToken();
    if (!token) {
      throw new Error('No token available');
    }
    const profile = await trpc.getProfile(token);
    user.value = profile;
    return profile;
  } catch (err: any) {
    error.value = err.message || 'Failed to fetch profile';
    // 如果 token 无效，清除认证信息
    if (err.message?.includes('UNAUTHORIZED')) {
      logout();
    }
    throw err;
  } finally {
    isLoading.value = false;
  }
}

// 清除错误
function clearError() {
  error.value = null;
}

// 导出认证 store
export const useAuthStore = () => ({
  // 状态
  user: user,
  isLoading: isLoading,
  error: error,
  isAuthenticated,
  
  // 方法
  login,
  register,
  logout,
  fetchProfile,
  clearError,
});
